package com.idelan.commonMessage.utils;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
* @Description:    java类作用描述
* @Author:         jzhou
* @CreateDate:     2018\7\17 0017 10:19
* @UpdateUser:     jzhou
* @UpdateDate:     2018\7\17 0017 10:19
* @UpdateRemark:   修改内容
* @Version:        1.0
*/
public class Mail163Util {
    public static int sendMail(String user,
                               String password,
                               String sender,
                               String received,
                               String subject,
                               String content,
                               String contentType) throws MessagingException {
        Properties prop=new Properties();
        prop.put("mail.host","smtp.163.com" );
        prop.put("mail.transport.protocol", "smtp");
        prop.put("mail.smtp.auth", true);
//使用java发送邮件5步骤
//1.创建sesssion
        int result=0;
        Session session=Session.getInstance(prop);
//开启session的调试模式，可以查看当前邮件发送状态
        session.setDebug(true);
//2.通过session获取Transport对象（发送邮件的核心API）
        Transport ts=session.getTransport();
//3.通过邮件用户名密码链接
        ts.connect(user, password);
//4.创建邮件
        MimeMessage msg=createSimpleMail(session,sender,received,subject,content,contentType);
//5.发送电子邮件
        if(msg!=null){
            result=1;
        }
        ts.sendMessage(msg, msg.getAllRecipients());
        return result;
    }
    public static MimeMessage createSimpleMail(Session session,String sender,
                                               String received,String subject,String content,
                                               String contentType) throws AddressException,MessagingException{
//创建邮件对象
        MimeMessage mm=new MimeMessage(session);
//设置发件人
        mm.setFrom(new InternetAddress(sender));
//设置收件人
        mm.setRecipient(Message.RecipientType.TO, new InternetAddress(received));
//设置抄送人
//        mm.setRecipient(Message.RecipientType.CC, new InternetAddress("15552218830@163.com"));

        mm.setSubject(subject);
        mm.setContent(content, contentType);
        return mm;
    }
    public static void main(String[] args) throws MessagingException {
        sendMail("15552218830@163.com","zjlove1314","15552218830@163.com",
                "1375749908@qq.com","测试","测试","text/html;charset=gbk");
    }


}